package wiki.hitime.stl.daq.manager;

import org.springframework.util.CollectionUtils;
import wiki.hitime.stl.daq.bean.db.DaqMsgBaseConfig;
import wiki.hitime.stl.daq.bean.dto.config.MsgBaseConfigDTO;
import wiki.hitime.stl.daq.mapper.DaqMsgBaseConfigMapper;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhangdaoping
 * @create 2019-07-18 15:31
 */
@Service
public class DaqMsgBaseConfigManager {

    private DaqMsgBaseConfigMapper daqMsgBaseConfigMapper;

    public DaqMsgBaseConfigManager(DaqMsgBaseConfigMapper daqMsgBaseConfigMapper) {
        this.daqMsgBaseConfigMapper = daqMsgBaseConfigMapper;
    }

    /**
     * 加载消息配置信息
     *
     * @param msgType 消息类型
     * @return
     */
    public Map<String, String> loadMsgBaseConfig(Integer msgType) {
        Example selectExample = new Example(DaqMsgBaseConfig.class, true, true);
        selectExample.createCriteria().andEqualTo("msgType", msgType).andEqualTo("isDelete", Boolean.FALSE);
        List<DaqMsgBaseConfig> detailConfigList = daqMsgBaseConfigMapper.selectByExample(selectExample);
        Map<String, String> configMap = new HashMap<>(detailConfigList.size());
        for (DaqMsgBaseConfig config : detailConfigList) {
            configMap.put(config.getConfigKey(), config.getConfigValue());
        }
        return configMap;
    }

    /**
     * 添加消息基础配置
     *
     * @param msgBaseConfigDTO
     */
    public void addMsgBaseConfig(MsgBaseConfigDTO msgBaseConfigDTO) {
        daqMsgBaseConfigMapper.insertList(this.convertDb(msgBaseConfigDTO));
    }

    private List<DaqMsgBaseConfig> convertDb(MsgBaseConfigDTO msgBaseConfigDTO) {
        List<DaqMsgBaseConfig> msgBaseConfigList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(msgBaseConfigDTO.getConfigValue())) {
            msgBaseConfigDTO.getConfigValue().forEach(nameValue -> {
                msgBaseConfigList.add(DaqMsgBaseConfig.builder()
                        .configName(msgBaseConfigDTO.getConfigName())
                        .msgType(msgBaseConfigDTO.getMsgType())
                        .configKey(nameValue.getName())
                        .configValue(nameValue.getValue())
                        .isDelete(Boolean.FALSE)
                        .build());
            });
        }
        return msgBaseConfigList;
    }
}
